package com.example.app06_component;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * 测试MenuActivity
 * OptionMenu：
 *  演示菜单显示，需要修改主题，将ActionBar显示出来
 *      res --> values --> theme
 *          <style name="Base.Theme.HelloApplication" parent="Theme.Material3.DayNight">
 *
 * ContextMenu：上下文菜单
 *
 *  长按某个视图对象显示，给需要显示上下文菜单的视图对象设置 setOnCreateContextMenuListener 监听
 *
 * @author lijiguo
 */
public class MenuActivity extends AppCompatActivity {

    private static final String TAG = "MenuActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        Log.i(TAG, "onCreate()");

        Button btnMenuShowCm = findViewById(R.id.btn_menu_show_cm);
        btnMenuShowCm.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                // 添加菜单项
                menu.add(0, 1, 0, "添加");
                menu.add(0, 4, 0, "删除");
            }
        });
    }

//    /**
//     * 用来显示Menu的方法
//     * 向Menu中添加Item
//     * @param menu The options menu in which you place your items.
//     *
//     * @return
//     */
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // 纯编码方式添加
//        menu.add(0, 2, 0, "添加");
//        menu.add(0, 3, 0, "删除");
//        return super.onCreateOptionsMenu(menu);
//    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 加载菜单资源文件
        getMenuInflater().inflate(R.menu.option_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 按钮菜单每一项的点击事件
     * @param item The menu item that was selected.
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_add) {
            Toast.makeText(this, "添加", Toast.LENGTH_SHORT).show();
        } else if(item.getItemId() == R.id.menu_delete) {
            Toast.makeText(this, "删除", Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()) {
            case 1:
                Toast.makeText(this, "添加", Toast.LENGTH_SHORT).show();
                break;
            case 4:
                Toast.makeText(this, "删除", Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onContextItemSelected(item);
    }
}